﻿using System;
using System.Collections.Generic;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Internal;
using Autodesk.AutoCAD.Runtime;

namespace AutoCADDotNetLibrary
{
    /// <summary>
    /// 同步发送命令（不能跨文档运行）
    /// </summary>
    public static class SendStringToExecuteSynchronize
    {
        private static List<Action> _actions = new List<Action>();

        /// <summary>
        /// 上下文的<see cref="Document.SendStringToExecute(string, bool, bool, bool)"/>同步运行SynchronizeMehtod
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="synchronizeMehtod">同步方法</param>
        public static void SendStringToExecuteSynchronizeMehtod(this Document doc, Action synchronizeMehtod)
        {
            if (_actions.Count == 0)
            {
                doc.CommandWillStart += InvokeMethod;
            }

            doc.SendStringToExecute("NullCommandSynchronizeMehtod ", true, false, false);
            _actions.Add(synchronizeMehtod);
        }

        //执行空命令，执行方法
        private static void InvokeMethod(object sender, CommandEventArgs e)
        {
            if ("NullCommandSynchronizeMehtod".ToUpper() == e.GlobalCommandName.Trim().ToUpper())//执行空命令，还原值
            {
                if (_actions.Count != 0)
                {
                    try//可能会异常
                    {
                        _actions[0]?.Invoke();
                    }
                    catch (System.Exception)
                    {
                        _actions.Clear();
                        ((Document)sender).CommandWillStart -= InvokeMethod;
                        throw;
                    }

                    _actions.RemoveAt(0);
                }

                if (_actions.Count == 0)
                {
                    ((Document)sender).CommandWillStart -= InvokeMethod;
                }
            }
        }



        static SendStringToExecuteSynchronize()
        {
            Utils.AddCommand(nameof(AutoCADDotNetLibrary), "___NullCommandSynchronizeMehtod", "___NullCommandSynchronizeMehtod", CommandFlags.NoHistory, () => { });
        }
        /// <summary>
        /// 空命令
        /// </summary>
        //[CommandMethod("___NullCommandSynchronizeMehtod", CommandFlags.NoHistory)]
        //public static void NullCommandSynchronizeMehtod()
        //{
        //}
    }
}
